package lin.an.food.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lin.an.food.entity.Food;
import lin.an.food.entity.FoodClicks;
import lin.an.food.mapper.FoodClicksMapper;
import lin.an.food.mapper.FoodMapper;
import lin.an.food.service.FoodClicksService;
import lin.an.food.vo.FoodClicksVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoulinq
 * @date 2025/4/24
 */
@Service
public class FoodClicksServiceImpl extends ServiceImpl<FoodClicksMapper, FoodClicks> implements FoodClicksService {
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Override
    public void likeAmount(int foodId) {
        LambdaQueryWrapper<FoodClicks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FoodClicks::getFoodId,foodId);
        FoodClicks foodClicks = this.getOne(queryWrapper);
        //已经存在的美食id，取出点击数再+1,不存在则添加记录。
        if(ObjectUtil.isNotEmpty(foodClicks)){
            int click = foodClicks.getClicks() + 1;
            foodClicks.setClicks(click);
            this.updateById(foodClicks);
        }else {
            FoodClicks foodClicks1 = new FoodClicks();
            foodClicks1.setFoodId(foodId);
            foodClicks1.setClicks(1);
            this.save(foodClicks1);
        }
    }
    
    @Override
    public List<FoodClicksVo> getTopClicks() {
        // 查询点击数最多的前10条记录
        LambdaQueryWrapper<FoodClicks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(FoodClicks::getClicks)
                .last("LIMIT 10");
        List<FoodClicks> foodClicksList = this.list(queryWrapper);
        
        List<FoodClicksVo> result = new ArrayList<>();
        
        // 遍历结果，获取美食名称
        for (FoodClicks foodClicks : foodClicksList) {
            FoodClicksVo vo = new FoodClicksVo();
            vo.setClicks(foodClicks.getClicks());
            
            // 查询美食名称
            Food food = foodMapper.selectById(foodClicks.getFoodId());
            if (food != null) {
                vo.setFoodName(food.getFoodName());
            } else {
                vo.setFoodName("未知美食");
            }
            
            result.add(vo);
        }
        
        return result;
    }
}
